import { Component, Injector, ViewEncapsulation, ViewChild, OnInit, EventEmitter, Output } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { MaterialChargeServiceProxy, OutboundInventoryOfMaterialInput, CreatePurposeOfMaterialInput, PurposeForBarcodeEditDto } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'yl2OutModal',
    templateUrl: './yl2-out-modal.component.html',
    //styleUrls: ['./yl2.component.less'],
    encapsulation: ViewEncapsulation.None
})

export class YL2OutModalComponent extends AppComponentBase {

    @ViewChild('secondModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    chargeId = 0;

    materialForProductId = "";

    quantity = 0;
    remark = '';
    barCode = '';
    pipeId = '';

    constructor(
        injector: Injector,
        private _outMaterialServiceProxy: MaterialChargeServiceProxy
    ) {
        super(injector);
    }

    show(chargeId: number, materialForProductId: string, barCode: string, pipeId: string): void {
        this.barCode = barCode;
        this.active = true;
        this.quantity = 0;
        this.remark = '';
        this.pipeId = pipeId;
        this.chargeId = chargeId;
        this.materialForProductId = materialForProductId;

        setTimeout(() => {
            this.modal.show();
        }, 0);
    }

    save(): void {

        if (!this.quantity) {
            this.notify.error('出库数量不能为0');
            return;
        }

        this.saving = true;
        var out = new OutboundInventoryOfMaterialInput();
        var cpo = new CreatePurposeOfMaterialInput();
        var pfb = new PurposeForBarcodeEditDto();
        pfb.barcode = this.barCode;
        cpo.materialForProductId = this.materialForProductId;
        cpo.purposeForBarcode = pfb;

        out.purposeOfMaterial = cpo;
        out.inventoryOfMaterialId = this.chargeId;
        out.quantity = this.quantity;
        console.log(out)
        this._outMaterialServiceProxy.outboundAsync(out, this.pipeId)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(result => {
                this.close();
                this.modalSave.emit(null);
                this.notify.success('出库成功');

            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

}
